<script lang="ts">
    import { onDestroy } from "svelte";
    import { clamp } from "./utils";

    const props = $props();
    let left = $state(clamp((props.value.hsl.h * 100) / 360, 0, 100));
    let container: any;
    const handleMouseDown = (e: any) => {
        if (typeof e.button === "number" && e.button !== 0) return false;
        handleChange(e);

        document.addEventListener("mousemove", handleChange, false);
        document.addEventListener("mouseup", onDragEnd, false);
    };

    const onDragEnd = (e: any) => {
        handleChange(e);
        document.removeEventListener("mousemove", handleChange);
        document.removeEventListener("mouseup", onDragEnd);
    };

    onDestroy(() => {
        document.removeEventListener("mousemove", handleChange);
        document.removeEventListener("mouseup", onDragEnd);
    });

    const handleChange = (e: any) => {
        e.preventDefault();
        e.stopPropagation();

        const { clientWidth } = container;
        const xOffset = container.getBoundingClientRect().left + window.screenX;
        const left = e.clientX - xOffset;
        if (left < 0) {
            change(0);
            return;
        }
        if (left > clientWidth) {
            change(100);
            return;
        }

        change((left * 100) / clientWidth);
    };

    const change = (percent: number) => {
        left = clamp(percent, 0, 100);

        const { h, s, l, a } = props.value.hsl;
        const newHue = clamp((percent / 100) * 360, 0, 360);

        if (h !== newHue) {
            props.onChange && props.onChange({ h: newHue, s, l, a, source: "hsl" });
        }
    };

    $effect(() => {
        left = clamp((props.value.hsl.h * 100) / 360, 0, 100);
    });
</script>

<div class="cm-color-picker-hue" bind:this={container}>
    <!-- svelte-ignore a11y_no_static_element_interactions -->
    <div class="cm-color-picker-hue-wrap" onmousedown={handleMouseDown}>
        <div class="cm-color-picker-hue-pointer" style={`top: 0; left: ${left}%`}></div>
    </div>
</div>
